<?php
namespace Admin\Controller;
use Think\Controller;

class ArticleController extends CommonController
{
    private $Article;
    private $Category;
    private $categories;

    function __construct()
    {
        parent::__construct();
        $this->Article = D('Article');
        $this->Category = D('category');
        $this->categories = $this->Category->reSort($this->Category->order('sort_order')->select());
    }

    public function create()
    {
        if($_POST){
            $file = array_filter($_POST['file']);
            $_POST['file']=implode(',',$file);
            //dump($_POST);
            //die;
            if (!$this->Article->create()) {
                $this->error($this->Article->getError());
            } else {
                //$this->Article->time = strtotime(I('post.time'));
                $this->Article->add();
                $this->redirect('lst');
            }
        }

        $this->assign('categories', $this->categories);
        $this->display();
    }

    public function lst()
    {
        $articles = $this->Article->order('category_id')->relation(true)->select();
        //dump($articles);
        //die;

        $count = $this->Article->count();

        $Page = new \Think\Page2($count, 3);

        $Page->setConfig('prev', '上一页');
        $Page->setConfig('next', '下一页');


        $show = $Page->show();
        $list = $this->Article->order('time desc')->relation(true)->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('list', $list);

        //p($list);
        //die;
        $this->assign('page', $show);

        //$this->assign('articles',$articles);
        //dump($articles);
        //die;

        $this->display();
    }

    public function store()
    {
        $file = array_filter($_POST['file']);
        $_POST['file']=implode(',',$file);
        //p($_POST['file']);
        //p($_POST);die;
        if (!$this->Article->create()) {
            $this->error($this->Article->getError());
        } else {
            //$this->Article->time = strtotime(I('post.time'));
            $this->Article->time=time();
            $this->Article->save();
            $this->success('编辑文章成功！', 'lst');
        }
    }

    public function edit()
    {
        $id = I('get.id');
        $article = $this->Article->relation(true)->find($id);

        $article['file']=explode(',',$article['file']);
        //dump($article);
        //die;

        $this->assign('article',$article);
        $this->assign('categories', $this->categories);
        $this->display();
    }

    public function del(){
        $id = I('get.id');
        if($this->Article->delete($id)){
            $this->success('删除文章成功！');
        }else{
            $this->error('删除文章失败，请重试！');
        }
    }

}